<?php
require 'ShoppingCart.php';
require 'ShoppingCartAuth.php';

class Shop extends ShoppingCart
{
    protected $database, $user, $password, $orderid = '';
    private $pdo = null, $isAuth = false, $sCartAuth = null;
    
    public function __construct($database, $user, $password)
    {
    	parent::__construct();
    	
        $this->database = $database;
        $this->user = $user;
        $this->password = $password;
    }

    public function getIsAuth()
    {
    	return $this->isAuth; 
    }
    
    public function logout()
    {
    	$this->orderid = null;
    	$this->isAuth = false;
    	$this->sCartAuth = null;
    }
    
    public function authAndOrder($userid, $password)
    {
        $this->sCartAuth = new ShoppingCartAuth($this->database, $this->user, $this->password);
        $this->isAuth = $this->sCartAuth->checkAuth($userid, $password);
        
        if ($this->isAuth)
        {
        	if (!isset($this->orderid))
            	$this->sCartAuth->createOrder($userid);
        	
        	if (isset($this->items))
        	{
	            try 
	            {
	            	foreach ($this->items as $key=>$value)
	            	{
	            		foreach ($value as $items=>$item)
	            		{
	            			$this->add($items, $item["Price"], $item["Quantity"]);
	            		}
	            	}
	            }
	            catch(PDOException $e)
	            {
	                throw new ErrorException("Databaseconnection is not available");
	            }
            	$this->items = null;
        	}
        }
        
        return $this->isAuth;
    }
 
    public function add($name, $price, $quantity)
    {
        if ($this->isAuth && isset($this->sCartAuth))
        {
            $this->sCartAuth->add($name, $price, $quantity);
        }
        else 
        {
            parent::add($name, $price, $quantity);
        }
    }
    
    public function delete($name, $quantity)
    {
        if ($this->isAuth && isset($this->sCartAuth))
        {
            $this->sCartAuth->delete($name, $quantity);
        }
        else 
        {
            parent::delete($name, $quantity);
        }
    }
    
    public function subTotal() 
    {
        if ($this->isAuth && isset($this->sCartAuth))
        {
            return $this->sCartAuth->subtotal();
        }
        else
        {
            return parent::subTotal();
        }
    }
    
    public function display()
    {
        if ($this->isAuth && isset($this->sCartAuth))
    	{
    	    return $this->sCartAuth->display();
    	}
    	else 
    	{
    		return parent::display();
    	}
    }
}